<template>
	<view class="message-page">
		<!-- 消息列表 -->
		<scroll-view class="message-list" scroll-y>
			<view class="message-item" v-for="(item, index) in messageList" :key="index" @click="viewDetail(item)">
				<view class="message-header">
					<text class="message-title">{{ item.title }}</text>
					<text class="message-time">{{ formatTime(item.time) }}</text>
				</view>
				<text class="message-content">{{ item.content }}</text>
				<view class="unread-badge" v-if="!item.read"></view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';

	// 消息列表
	const messageList = ref([]);

	// 格式化时间显示
	const formatTime = (timeStr) => {
		const date = new Date(timeStr);
		return `${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
	}

	// 查看消息详情
	const viewDetail = (item) => {
		// 如果消息未读，则标记为已读
		if (!item.read) {
			uni.request({
				url: `http://localhost:3000/messages/${item.id}`,
				method: 'PATCH',
				data: {
					read: true
				},
				success: () => {
					// 更新本地状态
					item.read = true;
					// 更新全局消息计数
					uni.$emit('updateMessageCount');
				}
			});
		}

		uni.navigateTo({
			url: `/pages/message/detail?id=${item.id}`
		});
	}

	// 加载消息列表
	const loadMessages = () => {
		uni.request({
			url: 'http://localhost:3000/messages',
			method: 'GET',
			success: (res) => {
				// 按时间降序排序
				messageList.value = res.data.sort((a, b) =>
					new Date(b.time) - new Date(a.time)
				);
			}
		});
	}

	// 监听消息计数更新事件
	uni.$on('updateMessageCount', () => {
		loadMessages();
	});

	// 页面加载时获取消息
	onLoad(() => {
		loadMessages();
	});

	// 页面显示时刷新数据
	onShow(() => {
		loadMessages();
	});
</script>
<style>
	.message-page {
		height: 100vh;
		background-color: #f5f5f5;
	}

	.message-list {
		height: 100%;
		padding: 20rpx;
		box-sizing: border-box;
	}

	.message-item {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		position: relative;
	}

	.message-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 16rpx;
	}

	.message-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.message-time {
		font-size: 24rpx;
		color: #999;
	}

	.message-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}

	.unread-badge {
		position: absolute;
		top: 24rpx;
		right: 24rpx;
		width: 16rpx;
		height: 16rpx;
		background-color: #FF5722;
		border-radius: 50%;
	}
</style>